<?php
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

$user_id = isset($_POST['user_id']) ? intval($_POST['user_id']) : 0;
$guide_id = isset($_POST['guide_id']) ? intval($_POST['guide_id']) : 0;
$action = isset($_POST['action']) ? $_POST['action'] : '';

if ($user_id <= 0 || $guide_id <= 0 || !in_array($action, ['add', 'remove'])) {
    echo json_encode([
        'status' => 'error',
        'message' => '参数错误'
    ]);
    exit;
}

try {
    if ($action === 'add') {
        $sql = "INSERT IGNORE INTO favorites (user_id, guide_id) VALUES (?, ?)";
    } else {
        $sql = "DELETE FROM favorites WHERE user_id = ? AND guide_id = ?";
    }

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ii", $user_id, $guide_id);
    
    if ($stmt->execute()) {
        echo json_encode([
            'status' => 'success',
            'message' => $action === 'add' ? '收藏成功' : '取消收藏成功'
        ]);
    } else {
        throw new Exception("操作失败");
    }

} catch (Exception $e) {
    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage()
    ]);
} finally {
    if (isset($stmt)) $stmt->close();
    $conn->close();
}
?> 